package com.partsoft.dits.exts;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.jar.JarFile;

public class JarClassPath implements ExtendsClassPath {
	
	private File file;
	
	private JarFile jarfile;
	
	public JarClassPath(String filename) {
		setJarFile(filename);
	}
	
	public JarClassPath(File file) {
		setJarFile(file);
	}

	public InputStream openStreamForClass(String name) {
		try {
            String jarname = name.replace('.', '/') + ".class";
            java.util.jar.JarEntry je = jarfile.getJarEntry(jarname);
            if(je != null) return jarfile.getInputStream(je);
        } catch(Throwable e) {}
		return null;
	}

	public URL findResource(String name) {
		try {
			java.util.jar.JarEntry je = jarfile.getJarEntry(name);
			if(je != null) return new URL("jar:" + file.toURI().toURL().toString() + "!/" + name);
        } catch(Throwable e) { }
        return null;
	}
	
	public void setJarFile(String jarfilename) {
		setJarFile(new File(jarfilename));
	}
	
	public void setJarFile(File file) {
		this.file = file;
	}
	
	public void setJarfile(JarFile jarfile) {
		this.jarfile = jarfile;
	}
	
	public void open() throws IOException {
		this.jarfile = new JarFile(file);
	}
	
	public JarFile getJarFile() {
		return this.jarfile;
	}
	
	String getAbsolutePath() {
		return file.getAbsolutePath();
	}
	
	public File getFile() {
		return file;
	}

	public void close() throws IOException {
		if (jarfile != null) jarfile.close();
		jarfile = null;
	}

}
